package org.fujene.search;

import org.fujene.communicate.SearchFlags;
import org.fujene.structure.SearchRangeTuple;
import org.fujene.structure.TimeRangeTuple;

public class SearchPackage{
	private String query;
	private byte[] type;
	private boolean andSearch;
	private int from, length;
	private SearchFlags flags;

	private SearchPackage(){}

	public static SearchPackage createPackage(String newQuery, int from, int length, byte[] type,
		boolean andSearch, int bLength, int mLength){
		SearchPackage pkg = new SearchPackage();
		pkg.query = newQuery;
		pkg.from = from;
		pkg.length = length;
		pkg.type = type;
		pkg.andSearch = andSearch;
		pkg.flags = new SearchFlags(bLength, mLength);

		return pkg;
	}
	
	public void setBinaryFlag(int index, byte value){
		this.flags.setBinaryFlags(index, value);
	}
	
	public byte[] binaryFlags(){
		return flags.getBinaryFlags();
	}
	
	public void setTimeRange(int rangeType, long rangeFrom, long rangeTo) {
		this.flags.setTimeRange(rangeType, rangeFrom, rangeTo);
	}
	
	public TimeRangeTuple timeRange() {
		return flags.getTimeRange();
	}
	
	public void setMultipleFlag(int index, byte rangeType, int rangeFrom, int rangeTo) {
		this.flags.setMultipleFlags(index, rangeType, rangeFrom, rangeTo);
	}
	
	public SearchRangeTuple[] multipleFlags() {
		return flags.getFlagRange();
	}
	
	public SearchFlags flags() {
		return flags;
	}
	
	public String query(){
		return query;
	}

	public int from(){
		return from;
	}

	public int length(){
		return length;
	}

	public void setLength(long[] results){
		int count = 0;
		if(results == null) {
			this.length = 0;
			return;
		}
		for(int i = 0; i < results.length; i++){
			if(results[i] != 0L) count++;
		}
		this.length = count;
	}
	
	public byte[] searchTypes() {
		return type;
	}

	public boolean searchType(int index){
		int typeIndex = index / 8;
		int indexBit = index % 8;
		int window = 1 << indexBit;
		if((type[typeIndex] << indexBit & window) != 0) return true;
		return false;
	}

	public boolean isAndSearch(){
		return andSearch;
	}
}
